import {Component, OnDestroy, OnInit} from '@angular/core';
import {PageTitleService} from "../page-title.service";
import { Location } from '@angular/common';


declare let AMap:any;

@Component({
  selector: 'app-navigation',
  templateUrl: './navigation.component.html',
  styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent implements OnInit ,OnDestroy {

  private map: any; // this is map object

  private transfer: any; // for transfer

  private geolocation: any;// location object

  ngOnDestroy(): void {
    this._pageTitle.isNavigation = false;
  }

  constructor(private _pageTitle: PageTitleService,
              private _location: Location,) {

  }

  ngOnInit() {
    this.map = new AMap.Map('map_container', {
      resizeEnable: true,
      zoom: 11,
      center: [116.397428,39.90923]
    });

    this._pageTitle.isNavigation = true;

    AMap.service('AMap.Transfer',() => {
      this.transfer = new AMap.Transfer({
        map: this.map,
        city: '北京市',
        panel: 'panel',// 公交城市
        // cityd: '乌鲁木齐,
        policy: AMap.TransferPolicy.LEAST_TIME // 乘车策略
      });
      console.log("map transfer inited!!");
    });

    // location
    this.map.plugin('AMap.Geolocation',() => {
      this.geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition:'RB'
      });
      this.map.addControl(this.geolocation);
      this.geolocation.getCurrentPosition();
      AMap.event.addListener(this.geolocation,'complete',this.onComplete);// 返回定位信息
      AMap.event.addListener(this.geolocation,'error',this.onError);// 返回定位出错信息
    });

  }

  //noinspection JSUnusedLocalSymbols
  /**
   * type: option value: AMap.Transfer|AMap.Walking|AMap.Driving
   * trans.search([{keyword:'北京市地震局(公交站)'},{keyword:'望京西园4区'}], function(status, result){

   * */
  searchPath(province: string, city: string, type: string): void {
    // 根据起、重点坐标查询公交换乘车线
    this.transfer.search([{
      keyword: '北京市地震局(公交站)'
    },{
      keyword: '望京西园4区'
    }],(status, result) => {
      console.log("map: " + status + ":result:" + result);
    });
  }

  clearPath() {
    this.transfer.clear();
  }

  goBack() {
    this._location.back();
  }

  private onComplete(data) {
    console.log("定位成功:" + data.valueOf());
  }

  private onError(data) {
    console.log("定位失败: "+data.valueOf());
  }
}
